package graphinterface;

import org.newdawn.slick.Color;
import org.newdawn.slick.GameContainer;
import org.newdawn.slick.Graphics;
import org.newdawn.slick.Image;
import org.newdawn.slick.SlickException;
import org.newdawn.slick.SpriteSheet;
import org.newdawn.slick.geom.Rectangle;

public class ImageButton extends MouseDetector{
	
	private SpriteSheet bSheet = null;
	private boolean persoName = false;

	public ImageButton(Image image) throws SlickException {
		super(new Rectangle(0, 0, image.getWidth()/3, image.getHeight()), new Color[3], "");
		bSheet = new SpriteSheet(image, image.getWidth()/3, image.getHeight());
	}
	
	public void draw(Graphics g, float x, float y){
		this.shape.setX(x);
		this.shape.setY(y);
		g.drawImage(bSheet.getSprite(state, 0), x, y);
		if(persoName){
			g.setColor(Color.black);
			g.drawString(this.name, 
					this.shape.getX()+(this.shape.getWidth()-g.getFont().getWidth(this.name))/2,
					this.shape.getY()+(this.shape.getHeight()-g.getFont().getHeight(this.name))/2);
		}
	}
	
	public void drawCentered(Graphics g, float x, float y){
		this.shape.setCenterX(x);
		this.shape.setCenterY(y);
		g.drawImage(bSheet.getSprite(state, 0), this.shape.getX(), this.shape.getY());
		if(persoName){
			g.setColor(Color.black);
			g.drawString(this.name, 
					this.shape.getX()+(this.shape.getWidth()-g.getFont().getWidth(this.name))/2,
					this.shape.getY()+(this.shape.getHeight()-g.getFont().getHeight(this.name))/2);
		}
	}
	
	public void update(GameContainer gc, int mouseButton){
		if (this.isInColision(gc.getInput().getMouseX(), gc.getInput().getMouseY())){
			if (gc.getInput().isMouseButtonDown(mouseButton)){
				this.setActual(MOUSE_DOWN);
				this.pushed = true;
			}else{
				this.setActual(MOUSE_OVER);
			}
		}
		else {
			this.setActual(NORMAL);
		}
	}
	
	public boolean isInColision(int mX, int mY){
		if (this.shape.contains(mX, mY)){
			Color color = bSheet.getSprite(state, 0)
						.getColor((int)(mX - this.shape.getX()), (int) (mY - this.shape.getY()));
			return color.getAlpha() > 0;
		}
		return false;
	}
	
	public void setPersoName(boolean usePersoName){
		this.persoName = usePersoName;
	}

}
